package com.qk.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 *
 * @author lyl
 * @created 2025/10/9 15:05
 * @description
 *
 */

public class CustomLocalDateTimeDeserializers extends JsonDeserializer<LocalDateTime> {

    // 支持多种日期时间格式
    private static final DateTimeFormatter ISO_LOCAL_FORMAT = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
    private static final DateTimeFormatter ISO_DATE_TIME_FORMAT = DateTimeFormatter.ISO_DATE_TIME;

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateStr = p.getValueAsString();
        if (dateStr == null || dateStr.isEmpty()) {
            return null;
        }

        try {
            // 首先尝试解析完整的ISO日期时间格式(带时区)
            return LocalDateTime.from(ISO_DATE_TIME_FORMAT.parse(dateStr));
        } catch (DateTimeParseException e) {
            try {
                // 如果失败，则尝试解析本地日期时间格式
                return LocalDateTime.parse(dateStr, ISO_LOCAL_FORMAT);
            } catch (DateTimeParseException ex) {
                // 如果还失败，则抛出异常
                throw new IOException("无法解析日期时间字符串: " + dateStr, ex);
            }
        }
    }
}

